package spsu.swe6733.assignment2;

public class PositiveInteger {
	
	private int n;
	private boolean valid;
	
	public PositiveInteger(){
			n = 0;
			valid = false;
		}
		

		/**
		*  @param  a input string. String can be null,
		*  @return long integer that is a valid integer in Java
		*/		
		
		public int validatePosInteger(String s)
		{
			int m=0;
			try
			{			
				m = Integer.parseInt( s );										// convert the String to an integer
				if(m<=0)
					throw new Exception();										//catches non positive integers
				this.setValid();
				return m;
			}
			catch ( NumberFormatException nfe )
			{
				System.out.println(s +" is not an integer!");					//catches all non integer exceptions
				System.out.println("Enter an integer Please.");   
				return 0;
			}
			catch (Exception nonPositiveNumberExeception) 					    //catches non positive integer exceptions
			{
				System.out.println(s +" is not a positive integer!");		
				System.out.println( "Enter a positive integer Please.");
				return -1;
			}
		}
		
		/**
		*  @param  long integer validation as a positive integer
		*  @return long integer as the sum of all integer from 1 to n
		*/	
			public  long loopSum()
			{
				long sum = 0;		
				
				for(long k=0; k<=this.n; k++)
					{
						sum = sum +  k;                             //Calculate sum
					}
					return sum;		
			}

			/**
			*  @param  long integer validated as a positive integer
			*  @return long integer as the sum of all integer from 1 to n
			*  Catches stack overflow error recursive call is too long
			*/	
				public  long recursiveSum(int n)
				{
					try
					{		
						if(n == 1)
						{
							return 1;									//Base case
						}
						else
						{
							return (n + (recursiveSum(n-1)));				//Recursive call
						}	
					}
					catch(StackOverflowError e)							//Catch stack overflow cal on large recursive call
					{
						System.out.print("Stack Overflow Error!");
						return n;
					}
					
				}
				/**
				*  @param  long integer validated as a positive integer
				*  @return long integer as the sum of all integer from 1 to n
				*/	
					public  long arithmeticSum()
					{
						long sum = 0;		
						long m = this.n;
						sum = (m*m + m)/2;									//Calculate sum
						return sum;			
					}	
		
					public boolean isValid()
					{
						return valid;
					}
					
					public void setValid()
					{
						this.valid =true;
					}
					
					public int getN()
					{
						return n;
					}
					
					public void setN(String s)
					{
						this.n = validatePosInteger(s);
					}
		
	}

